package com.baihan.angus.app.game.busshow.adps;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.baihan.angus.app.game.busshow.R;
import com.baihan.angus.app.game.common.bean.response.ScriptRole;
import com.baihan.angus.app.game.common.util.ImageLoader;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;

import java.util.List;

public class SelectRoleAdp extends RecyclerView.Adapter {

    private Context mContext;
    private List<ScriptRole> mRoleList;
    private RecyclerView mRecyclerView;
    private int checkPositon = -1;

    public SelectRoleAdp(Context mContext, List<ScriptRole> mRoleList) {
        this.mContext = mContext;
        this.mRoleList = mRoleList;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_select_role, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        ViewHolder vh = (ViewHolder) holder;

        ScriptRole roleItem = mRoleList.get(position);

        vh.tvName.setText(roleItem.getName());
        ImageLoader.loadImage(mContext, vh.ivAvatar, roleItem.getAvatar(), R.mipmap.ic_test_bg, 0);

        vh.tvName.setBackgroundResource(roleItem.isSelected() ? R.drawable.shape_vote_selected_bg : R.drawable.shape_vote_unselected_bg);

        vh.flItem.setOnClickListener(v -> {
            if (checkPositon >= 0) {
                mRoleList.get(checkPositon).setSelected(false);
            }

            roleItem.setSelected(!roleItem.isSelected());

            // 保存选项
            checkPositon = holder.getLayoutPosition();
            notifyDataSetChanged();
        });

    }

    @Override
    public int getItemCount() {
        return mRoleList.size();
    }

    /**
     * 绑定recycleview
     *
     * @param recyclerView
     */
    public void bindRecycleView(RecyclerView recyclerView) {
        mRecyclerView = recyclerView;
        recyclerView.setAdapter(this);
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        TextView tvName;
        QMUIRadiusImageView ivAvatar;
        FrameLayout flItem;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvName = itemView.findViewById(R.id.tvName);
            ivAvatar = itemView.findViewById(R.id.ivAvatar);
            flItem = itemView.findViewById(R.id.flItem);
        }
    }

}
